package com.itcs.box.server.resolver;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.itcs.box.domain.BoxData;
import com.itcs.box.domain.BoxRequest;
import com.itcs.box.domain.BoxResponse;
import com.itcs.box.server.callback.BoxCallBack;
import com.itcs.box.server.server.NettyChannelMap;
import com.itcs.box.util.LogUtils;
import com.itcs.dubbo.service.DubboService;

import io.netty.channel.ChannelHandlerContext;

/**
 * 登录解析类
 * 
 * @author LiuPeng
 * @date 2017年12月12日
 * 
 */
@Component
public class Box1001Resolver implements MsgResolverAdapter {

	private ExecutorService executorService = Executors.newFixedThreadPool(10);

	private Log logger = LogFactory.getLog(getClass());

	// @Autowired
	// private StringRedisTemplate stringRedisTemplate;

	@Resource(name = "itcsApp")
	private DubboService itcsApp;

	@Override
	public boolean support(BoxRequest boxRequest) {
		return "1001".equals(boxRequest.getMessgeType());
	}

	@Override
	public void resolve(final ChannelHandlerContext channelHandlerContext, BoxRequest boxRequest) {

		// NettyChannelMap.add(boxRequest.getData().getDeviceId(), (SocketChannel)
		// channelHandlerContext.channel());

		BoxData data = boxRequest.getData();
		String deviceId = data.getDeviceId();

		ChannelHandlerContext oldChannel = NettyChannelMap.get(deviceId);

		if (oldChannel != null) {
			if (channelHandlerContext != oldChannel) {
				// 如果两个通道不是同一个
				try {
					logger.warn(LogUtils.build("1001", "通讯盒登录", "通讯盒:" + deviceId + ",已登录连接与当前通道不一致，强制关闭老的连接",
							JSON.toJSONString(boxRequest)));
					oldChannel.disconnect();
					oldChannel.close();
				} catch (Exception e) {
					logger.error("强制关闭netty连接异常", e);
				}
			}
		}

		logger.info(LogUtils.build("1001", "通讯盒登录", "通讯盒:" + boxRequest.getData().getDeviceId(),
				JSON.toJSONString(boxRequest)));

		Send2AppThread appThread = new Send2AppThread(itcsApp, channelHandlerContext, boxRequest, new BoxCallBack() {
			@Override
			public void callback(BoxResponse boxResponse) {
				String result = boxResponse.getData().getResult();
				String deviceId = boxResponse.getData().getDeviceId();
				String channelId = boxResponse.getChannelId();
				// 清除channelId,防止返回给盒子
				boxResponse.setChannelId(null);
				if ("1".equals(result)) {
					logger.info(LogUtils.build("1001", "通讯盒登录", "通讯盒:" + deviceId + " 登录验证成功"));
					NettyChannelMap.add(deviceId, channelId, channelHandlerContext);
				} else {
					try {
						channelHandlerContext.disconnect();
						channelHandlerContext.close();
					} catch (Exception e) {
						logger.error("强制关闭netty连接异常", e);
					}
					logger.warn(LogUtils.build("1001", "通讯盒登录", "通讯盒:" + deviceId + " 登录验证失败,断开连接,result:" + result));
				}
			}
		});

		executorService.execute(appThread);

		// ValueOperations<String, String> opsValue = stringRedisTemplate.opsForValue();
		//
		// stringRedisTemplate.convertAndSend(BoxConstants.PUBSUB_BOXID_CHECK,
		// deviceId);
		//
		// try {
		// Thread.sleep(100);
		// } catch (InterruptedException e) {
		// }
		//
		// boolean hasLogin = false;
		//
		// String value = opsValue.get(BoxIdCheckTopicResolver.KEY_PREFIX + deviceId);
		// if(value!=null) {
		// logger.info(LogUtils.build("1001", "通讯盒登录",
		// "通讯盒:" + boxRequest.getData().getDeviceId() + "已登录,正在检测已登录连接是否正常"));
		//
		// for (int i = 0; i < 20; i++) {
		// value = opsValue.get(BoxIdCheckTopicResolver.KEY_PREFIX + deviceId);
		// if(BoxIdCheckTopicResolver.STATUS_正常.equals(value)) {
		// hasLogin = true;
		// break;
		// }else if(BoxIdCheckTopicResolver.STATUS_异常.equals(value)) {
		// break;
		// }
		// try {
		// Thread.sleep(50);
		// } catch (InterruptedException e) {
		// }
		// }
		// stringRedisTemplate.delete(BoxIdCheckTopicResolver.KEY_PREFIX+deviceId);
		// }
		//
		//
		//
		// if (!hasLogin) {
		// NettyChannelMap.add(deviceId, channelHandlerContext);
		//
		// logger.info(LogUtils.build("1001", "通讯盒登录", "通讯盒:" +
		// boxRequest.getData().getDeviceId(),
		// JSON.toJSONString(boxRequest)));
		//
		// Send2AppThread appThread = new Send2AppThread(itcsApp, channelHandlerContext,
		// boxRequest);
		// executorService.execute(appThread);
		// } else {// 如果已经存在
		// data.setResult("9");
		// data.setMessResult("重复登录");
		// ByteBuf byteBuf =
		// Unpooled.wrappedBuffer(JSON.toJSONString(data).getBytes(BoxConstants.CHARSET_UTF8));
		// channelHandlerContext.writeAndFlush(byteBuf);
		//
		// if (channelHandlerContext != NettyChannelMap.get(deviceId)) {
		// // 如果两个通道不是同一个
		// try {
		// logger.warn(LogUtils.build("1001", "通讯盒登录",
		// "通讯盒:" + boxRequest.getData().getDeviceId() +
		// ",重复登录,且已登录连接与当前通道不一致，强制关闭当前连接",
		// JSON.toJSONString(boxRequest)));
		// channelHandlerContext.disconnect();
		// channelHandlerContext.close();
		// } catch (Exception e) {
		// logger.error("强制关闭netty连接异常", e);
		// }
		// } else {
		// logger.warn(
		// LogUtils.build("1001", "通讯盒登录", "通讯盒:" + boxRequest.getData().getDeviceId() +
		// ",同一连接，重复登录"));
		// }
		// }
	}

}
